# ==========================================================================#
#                             客户端通信线程
# 功能：客户端通信
# ==========================================================================#
import json

from PyQt5.QtCore import QThread

import global_var

class Thread_Recv_Send(QThread):
    def __init__(self, clientsocket, addr, data_signal):
        super().__init__()
        self.clientsocket = clientsocket
        self.data_signal = data_signal
        self.addr = addr

        self.recved = None

    def run(self):  # 重写run方
        while True:
            self.recved = self.clientsocket.recv(256)
            if self.recved:
                # 读取的字节数据是bytes类型，需要解码为字符串
                info = self.recved.decode()
                # 找到addr在clinet_addrs中的索引,判断智能体的ID
                index = global_var.get_index_client_addrs(self.addr)
                info = info[info.index("{"):info.index("}") + 1]
                print(index + 1, '号智能体发来消息:', info)

                if '{' in info:
                    # 转化为字典
                    info = json.loads(info)
                    # 向字典中添加ID键
                    info["ID"] = index + 1
                    self.data_signal.emit(json.dumps(info))
                else:
                    self.data_signal.emit(info)

                # 发送的数据类型必须是bytes，所以要编码
                # self.clientsocket.send(f'{info}'.encode())
            else:
                # 找到addr在clinet_addrs中的索引,判断智能体的ID
                index = global_var.get_index_client_addrs(self.addr)
                print(index+1, '号客户端', self.addr, '退出')
                # 找到addr在clinet_addrs中的索引
                index = global_var.get_index_client_addrs(self.addr)
                # 按照索引删除列表中的元素
                global_var.del_client_addrs(index)  # 删除客户端的addr
                global_var.del_clientsockets(index)  # 删除客户端的socket
                global_var.del_Robot_list(index)  # 删除智能体列表中的相应Robot对象
                global_var.del_Thread_recv_send_list(index)
                global_var.set_client_num(global_var.get_client_num() - 1)
                global_var.set_connect_change(True)
                break
